const multer = require("multer");
const path = require("path");
const fs = require("fs-extra");

// 确保上传目录存在
const uploadDir = path.join(__dirname, "../public/images/avatar");
fs.ensureDirSync(uploadDir);

// 配置 Multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    },
});

// 文件过滤器 - 只允许图片
const fileFilter = (req, file, cb) => {
    if (file.mimetype.startsWith("image/")) {
        cb(null, true);
    } else {
        cb(new Error("只允许上传图片文件"), false);
    }
};

// 配置 Multer 实例
const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 5 * 1024 * 1024, // 限制5MB
    },
});

module.exports = {
    upload,
};
